package com.tools.handler.analysis;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tools.common.result.Result;
import com.tools.handler.StepHandler;
import com.tools.pojo.data.MedicalAnalysisRequestDTO;
import com.tools.pojo.data.PatientDTO;
import com.tools.pojo.workflow.bo.StepContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class MedicalDataSplitStepHandler implements StepHandler {

    private static final String STEP_CODE = "DATA_SPLIT";

    @Override
    public String getStepCode() {
        return STEP_CODE;
    }

    @Override
    public Result<?> execute(StepContext context) {
        try {
            log.info("开始执行医疗数据拆分步骤，流程实例ID: {}", context.getFlowInstanceId());

            // 获取解析后的医疗数据DTO

            Map<String, Object> contextData = context.getContextData();
            Object data = contextData.get("medicalRequestDTO");
            MedicalAnalysisRequestDTO medicalRequestDTO;
            if (data instanceof Map) {
                ObjectMapper objectMapper = new ObjectMapper();
                medicalRequestDTO = objectMapper.convertValue(data, MedicalAnalysisRequestDTO.class);
            } else if (data instanceof MedicalAnalysisRequestDTO) {
                medicalRequestDTO = (MedicalAnalysisRequestDTO) data;
            } else {
                throw new IllegalStateException("未知的数据类型");
            }

//            MedicalAnalysisRequestDTO medicalRequestDTO = context.getContextData(
//                    "medicalRequestDTO", MedicalAnalysisRequestDTO.class);

            if (medicalRequestDTO == null) {
                return Result.fail("未找到已解析的医疗数据DTO");
            }

            // 拆分患者数据
            List<Map<String, Object>> patientRecords = splitPatientData(medicalRequestDTO);

            // 将拆分后的数据存入上下文
            context.putContextData("dataList", patientRecords);
            context.putContextData("totalPatients", patientRecords.size());
            context.putContextData("totalRecords", patientRecords.size());

            // 记录患者统计信息
            Map<String, Object> patientStats = calculatePatientStatistics(medicalRequestDTO);
            context.putContextData("patientStatistics", patientStats);

            log.info("医疗数据拆分步骤执行成功，共拆分成 {} 个患者记录", patientRecords.size());
            return Result.success("医疗数据拆分完成", patientStats);

        } catch (Exception e) {
            log.error("医疗数据拆分步骤执行失败", e);
            return Result.fail("医疗数据拆分失败: " + e.getMessage());
        }
    }

    /**
     * 拆分患者数据，每个患者生成一条独立记录
     */
    private List<Map<String, Object>> splitPatientData(MedicalAnalysisRequestDTO medicalRequestDTO) {
        List<Map<String, Object>> patientRecords = new ArrayList<>();

        List<PatientDTO> patientDtos = medicalRequestDTO.getPatientDtos();
        if (patientDtos == null || patientDtos.isEmpty()) {
            log.warn("未找到患者数据");
            return patientRecords;
        }

        // 为每个患者创建独立记录
        for (int i = 0; i < patientDtos.size(); i++) {
            PatientDTO patientDto = patientDtos.get(i);

            // 创建患者记录，包含公共信息和单个患者数据
            Map<String, Object> patientRecord = new HashMap<>();

            // 添加公共信息
            patientRecord.put("sysCode", medicalRequestDTO.getSysCode());
            patientRecord.put("rule_ids", medicalRequestDTO.getRuleIds());
            patientRecord.put("task_id", medicalRequestDTO.getTaskId());
            patientRecord.put("trig_scen", medicalRequestDTO.getTrigScen());
            patientRecord.put("record_index", i);
            patientRecord.put("total_patients", patientDtos.size());

            // 添加单个患者DTO
            patientRecord.put("patient_dto", patientDto);

            patientRecords.add(patientRecord);
        }

        return patientRecords;
    }

    /**
     * 计算患者统计信息
     */
    private Map<String, Object> calculatePatientStatistics(MedicalAnalysisRequestDTO requestDTO) {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalPatients", requestDTO.getPatientDtos().size());

        // 性别统计
        long maleCount = requestDTO.getPatientDtos().stream()
                .filter(patient -> "1".equals(patient.getGend()))
                .count();
        long femaleCount = requestDTO.getPatientDtos().stream()
                .filter(patient -> "2".equals(patient.getGend()))
                .count();

        stats.put("maleCount", maleCount);
        stats.put("femaleCount", femaleCount);
        stats.put("genderRatio", String.format("%.1f%%",
                (double) femaleCount / requestDTO.getPatientDtos().size() * 100));

        // 就诊类型统计
        Map<String, Long> medTypeStats = new HashMap<>();
        for (PatientDTO patient : requestDTO.getPatientDtos()) {
            var primaryEncounter = patient.getPrimaryEncounter();
            if (primaryEncounter != null && primaryEncounter.getMedType() != null) {
                medTypeStats.merge(primaryEncounter.getMedType(), 1L, Long::sum);
            }
        }
        stats.put("medTypeStats", medTypeStats);

        // 主要诊断统计
        Map<String, Long> diagnosisStats = new HashMap<>();
        for (PatientDTO patient : requestDTO.getPatientDtos()) {
            String mainDiagnosis = patient.getMainDiagnosis();
            if (mainDiagnosis != null) {
                diagnosisStats.merge(mainDiagnosis, 1L, Long::sum);
            }
        }
        stats.put("diagnosisStats", diagnosisStats);

        return stats;
    }


}
